package top.dimples.service.impl;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.dimples.service.BarkService;

/**
 * @author Dimples_YJ
 * @date 2021/12/7
 */
@Slf4j
@Service
public class BarkServiceImpl implements BarkService {

    @Value("${bark.enable}")
    private Boolean enable;

    @Value("${bark.url}")
    private String url;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 异步通知开发者的 iPhone
     *
     * @param title 通知的标题
     * @param msg   通知的消息内容
     * @return 是否通知成功
     */
    @Async
    @Override
    public Boolean notifyMyIPhone(String title, String msg) {
        if (enable) {
            ResponseEntity<BarkRespEntity> entity = restTemplate.getForEntity(StrUtil.format("{}/{}/{}", url, title, msg), BarkRespEntity.class);
            BarkRespEntity barkRespEntity = entity.getBody();
            log.info("发送通知给开发者的手机");
            return "200".equals(barkRespEntity.getCode());
        }
        return false;
    }


    /**
     * Bark 响应实体
     */
    @Data
    private static class BarkRespEntity {
        private String code;
        private String message;
        private String timestamp;

    }

}
